package com.acdc.wechat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.acdc.wechat.service.WechatPayService;
import com.acdc.wechat.service.WechatRefundService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.core.domain.AjaxResult;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信支付控制器
 */
@RestController
@RequestMapping("/wechat/pay")
public class WechatPayController {

    private static final Logger log = LoggerFactory.getLogger(WechatPayController.class);

    @Autowired
    private WechatPayService wechatPayService;

    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private WechatRefundService wechatRefundService;

    /**
     * 创建支付订单
     * @param request 支付请求参数
     * @return 支付参数
     */
    @PostMapping("/create")
    public AjaxResult createOrder(@RequestBody PayRequest request) {
        try {
            log.info("收到支付订单创建请求: {}", request);
            
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysUser user = userService.selectUserById(loginUser.getUser().getUserId());
            
            log.info("用户信息: userId={}, openId={}", user.getUserId(), user.getOpenId());
            
            Map<String, String> payParams = wechatPayService.createOrder(
                request.getTotalAmount() * 100,
                user.getOpenId(),
                request.getMeterNo()
            );
            
            log.info("生成的支付参数: {}", payParams);
            
            return AjaxResult.success(payParams);
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 申请退款
     * @param request 退款请求参数
     * @return 退款结果
     */
    @PostMapping("/refund")
    public AjaxResult createRefund(@RequestBody RefundRequest request) {
        try {
            Map<String, Object> refundResult = wechatRefundService.createRefund(
                request.getOutTradeNo(),
                request.getRefundAmount()
            );
            return AjaxResult.success(refundResult);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 支付结果通知回调
     * @param request HTTP请求
     * @return 处理结果
     */
    @PostMapping("/notify")
    public String handlePayNotify(HttpServletRequest request) {
        try {
            // 获取微信支付回调的请求头
            String nonce = request.getHeader("Wechatpay-Nonce");
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String signature = request.getHeader("Wechatpay-Signature");
            
            // 获取请求体数据
            String notifyData = getRequestBody(request);
            
            // 处理支付通知
            return wechatPayService.handlePayNotify(notifyData, nonce, timestamp, signature);
        } catch (Exception e) {
            log.error("处理支付通知失败", e);
            return "{\"code\":\"FAIL\",\"message\":\"处理失败\"}";
        }
    }

    /**
     * 退款结果通知回调
     * @param request HTTP请求
     * @return 处理结果
     */
    @PostMapping("/refund-notify")
    public String handleRefundNotify(HttpServletRequest request) {
        try {
            // 获取微信支付回调的请求头
            String nonce = request.getHeader("Wechatpay-Nonce");
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String signature = request.getHeader("Wechatpay-Signature");
            
            // 获取请求体数据
            String notifyData = getRequestBody(request);
            
            // 处理退款通知
            return wechatRefundService.handleRefundNotify(notifyData, nonce, timestamp, signature);
        } catch (Exception e) {
            log.error("处理退款通知失败", e);
            return "{\"code\":\"FAIL\",\"message\":\"处理失败\"}";
        }
    }

    /**
     * 查询退款状态
     * @param outRefundNo 退款单号
     * @return 退款状态
     */
    @GetMapping("/refund/query/{outRefundNo}")
    public ResponseEntity<Map<String, Object>> queryRefund(@PathVariable String outRefundNo) {
        try {
            Map<String, Object> refundStatus = wechatRefundService.queryRefund(outRefundNo);
            return ResponseEntity.ok(refundStatus);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取微信JSSDK配置
     * @param url 当前页面URL
     * @return JSSDK配置参数
     */
    @GetMapping("/jssdk/config")
    public AjaxResult getJSSDKConfig(@RequestParam String url) {
        try {
            Map<String, String> config = wechatPayService.getJSSDKConfig(url);
            return AjaxResult.success(config);
        } catch (Exception e) {
            return AjaxResult.error("获取JSSDK配置失败: " + e.getMessage());
        }
    }

    /**
     * 获取请求体数据
     */
    private String getRequestBody(HttpServletRequest request) {
        try {
            java.io.BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 支付请求参数
     */
    public static class PayRequest {
        private int totalAmount;
        private String openid;
        private String meterNo;

        // Getters and Setters
        
        public int getTotalAmount() { return totalAmount; }
        public void setTotalAmount(int totalAmount) { this.totalAmount = totalAmount; }
                
        public String getOpenid() { return openid; }
        public void setOpenid(String openid) { this.openid = openid; }

        public String getMeterNo() { return meterNo; }
        public void setMeterNo(String meterNo) { this.meterNo = meterNo; }
    }

    /**
     * 退款请求参数
     */
    public static class RefundRequest {
        private String outTradeNo;
        private int refundAmount;

        // Getters and Setters
        public String getOutTradeNo() { return outTradeNo; }
        public void setOutTradeNo(String outTradeNo) { this.outTradeNo = outTradeNo; }
        
        public int getRefundAmount() { return refundAmount; }
        public void setRefundAmount(int refundAmount) { this.refundAmount = refundAmount; }
        
    }
}
